<?php

jimport('joomla.client.ftp');

class FtpHelper {

	var $package;
	var $db;
	var $ftp;

	function __construct() {
		$this->db = JFactory::getDBO();
		$ftp = new JFTP();
		$this->ftp =& $ftp->getInstance();
	}
	
	/**
	 * FTP test method
	 */
	function isFtpValid($address, $ftpPort, $user, $pass) {
		
		//TODO get data from database
		$host = $address;
		$port = $ftpPort;
		$ftpUser = $user;
		$ftpPass = $pass;
		
		if($this->ftp->connect($host, $port)) {
			if($this->ftp->isConnected()) {
				if($this->ftp->login($ftpUser, $ftpPass)) {
					return true;
				}
				else {
					return false;
				}
			}
			else {
				return false;
			}
		}
		else {
			return false;
		}
	}

	function setPackage($packagefile) {
		$this->package = $packagefile;
	}

	function transferPackage($instanceName) {

		$this->db->setQuery("SELECT * FROM #__easiv2_instances WHERE name ='".$instanceName."'");
		$httpaddress = $this->db->loadObject()->http_address;
		$ftpaddress = $this->db->loadObject()->ftp_host;
		$port = $this->db->loadObject()->port;
		$user = $this->db->loadObject()->ftp_user;
		$pass = $this->db->loadObject()->ftp_pass;

		if($this->ftp->connect($ftpaddress, $port)) {
			if($this->ftp->login($user, $pass)) {
				/*
				 * transfer package to remotes directory
				 */
				$lastSlash = strrpos($this->package, DS);
				$packagename = substr($this->package, $lastSlash+1); //+1 because the last found slash is included otherwise

				$this->ftp->store($this->package, "/components/com_easiv2/repository/".$packagename);

				return $packagename;
			}
			else {
				echo "login failed";
				return null;
			}
		}
		else {
			echo "Could not connect to FTP.";
			return null;
		}
	}
}